package com.estun.backroundManagementService.config.threadPool;
/*
 * @author pengbo
 * @date 2024/4/3 11:19
 * @description
 */


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.estun.backroundManagementService.config.factoryMes.ApiCaller;
import com.estun.backroundManagementService.config.properties.ApiInfoProperties;
import com.estun.backroundManagementService.config.properties.LineInfoProperties;
import com.estun.backroundManagementService.domain.factoryMes.request.ProductInfoRequest.ProductInfoData;
import com.estun.backroundManagementService.domain.factoryMes.request.base.BaseMesRequest;
import com.estun.backroundManagementService.domain.factoryMes.request.base.BaseMesResponse;
import com.estun.backroundManagementService.modules.position.service.DeviceService;
import com.estun.backroundManagementService.modules.process.service.ProcessDetailService;
import com.estun.backroundManagementService.modules.product.mapper.ProductValueThresholdMapper;
import com.estun.backroundManagementService.modules.product.model.ProductPassStation;
import com.estun.backroundManagementService.modules.product.model.ProductValue;
import com.estun.backroundManagementService.modules.product.model.ProductValueThreshold;
import com.estun.backroundManagementService.modules.product.service.*;
import com.estun.backroundManagementService.modules.workOrder.dto.WorkOrderEntity;
import com.estun.backroundManagementService.modules.workOrder.service.WorkOrderService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
@EnableAsync
public class AsyncTask {
    @Autowired
    private  ApiCaller apiCaller;
    @Autowired
    private  LineInfoProperties lineInfoProperties;
    @Autowired
    private ProductValueService productValueService;
    @Autowired
    private  ApiInfoProperties apiInfoProperties;
    @Autowired
    private  ProcessDetailService processDetailService;
    @Autowired
    private ProductValueThresholdMapper productValueThresholdMapper;
    private static final ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 生产过程数据推送
     */
    @Async("myTaskAsyncPool")
    public Boolean pushProductInfo(ProductPassStation productStationTime, WorkOrderEntity workOrder, String productNo) throws JsonProcessingException {
        BaseMesRequest baseMesRequest =new BaseMesRequest<>();
        List<ProductInfoData> data = new ArrayList<>();
        String stationId = productStationTime.getPassStationId();
        Long productId = productStationTime.getProductId();
        long beginTime = System.currentTimeMillis();
        log.info("【推送value数据new】推送开始 productId:{},stationId:{}", productId, stationId);
        List<ProductValue> valueList = productValueService.getByProductIdAndStationId(productId, stationId);
        for (ProductValue value : valueList) {
            String realValue ="";
            // 处理data中的数据，取出最大值最后显示
            if(value.getValue() == null){
                String[] parts = value.getData().split(",");
                double max = Double.MIN_VALUE;
                for (String part : parts) {
                    double parseDouble = Double.parseDouble(part.trim());
                    if (parseDouble > max) {
                        max = parseDouble;
                    }
                }
                DecimalFormat df = new DecimalFormat("#.##");
                realValue = df.format(max);
            }else {
                realValue =String.valueOf(value.getValue());
            }
            // 处理日期格式
            LocalDateTime now = value.getCreateTime();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = now.format(formatter);
            // 处理阈值
            String minThreshold ="";
            String maxThreshold ="";
            String isQualified ="1";
            String name = value.getName();
            QueryWrapper<ProductValueThreshold> queryWrapper =new QueryWrapper<>();
            queryWrapper.eq("name",name);
            queryWrapper.eq("station_id",value.getStationId());
            List<ProductValueThreshold> productValueThresholdList = productValueThresholdMapper.selectList(queryWrapper);
            if(!productValueThresholdList.isEmpty()){
                for (ProductValueThreshold productValueThreshold : productValueThresholdList) {
                    String thresholdType = productValueThreshold.getThresholdType();
                    String threshold = productValueThreshold.getValue();
                    if("max".equals(thresholdType)){
                        maxThreshold = threshold;
                    }else if("min".equals(thresholdType)){
                        minThreshold = threshold;
                    }
                }
                // 判断真实值是否在阈值内
                if(StringUtils.isNotEmpty(maxThreshold) && StringUtils.isNotEmpty(minThreshold)){
                    double realValueNum = Double.parseDouble(realValue);
                    double minThresholdNum = Double.parseDouble(minThreshold);
                    double maxThresholdNum = Double.parseDouble(maxThreshold);
                    if (realValueNum >= minThresholdNum && realValueNum <= maxThresholdNum) {
                        isQualified ="0";
                    }
                }else if(StringUtils.isNotEmpty(maxThreshold) && StringUtils.isEmpty(minThreshold)){
                    double realValueNum = Double.parseDouble(realValue);
                    double maxThresholdNum = Double.parseDouble(maxThreshold);
                    if (realValueNum <= maxThresholdNum) {
                        isQualified ="0";
                    }
                }else if(StringUtils.isEmpty(maxThreshold) && StringUtils.isNotEmpty(minThreshold)){
                    double realValueNum = Double.parseDouble(realValue);
                    double minThresholdNum = Double.parseDouble(minThreshold);
                    if (realValueNum >= minThresholdNum) {
                        isQualified ="0";
                    }
                }
            }
            ProductInfoData productInfoData = new ProductInfoData();
            productInfoData.setLineCode(lineInfoProperties.getLineCode());
            productInfoData.setStationCode(stationId);
            productInfoData.setMaterialCode(workOrder.getMaterialCode());
            productInfoData.setMaterialName(workOrder.getMaterialName());
            productInfoData.setMaterialVersion(workOrder.getMaterialVersion());
            productInfoData.setSnNumber(productNo);
            productInfoData.setOperationCode(processDetailService.getProcessCodeByStationCode(stationId));
            productInfoData.setParamName(value.getName());
            productInfoData.setRealValue(realValue);
            productInfoData.setStandardValue("");
            productInfoData.setParamRange1(minThreshold);
            productInfoData.setParamRange2(maxThreshold);
            productInfoData.setCheckStartTime("");
            productInfoData.setCheckEndTime(formattedDateTime);
            productInfoData.setIsQualified(isQualified);
            data.add(productInfoData);
        }
        baseMesRequest.setData(data);
        if(data.isEmpty()){
            return false;
        }
        BaseMesResponse mesResponse = apiCaller.post(apiInfoProperties.getTestInformation(), baseMesRequest, BaseMesResponse.class);
        boolean success = mesResponse.isSuccess();
        if (!success) {
            log.error("【推送value数据】推送失败 productId:{},stationId:{},msg:{}", productId, stationId, mesResponse.getMesg());
        }
        log.info("【推送value数据new】推送成功 productId:{},stationId:{},msg:{},推送耗时:{},body:{}", productId, stationId, mesResponse.getMesg(),System.currentTimeMillis() - beginTime,objectMapper.writeValueAsString(baseMesRequest));
        return success;
    }
}
